<?php

namespace App\Service;

use App\Traits\JsonResponse;
use Illuminate\Support\Facades\Log;

class HttpService
{

    use JsonResponse;

    /**
     * 发送HTTP请求
     * @param $url
     * @param string $type
     * @param array $params
     * @return array|bool|false|float|int|object|string|null
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function HttpRequest($url, $type = 'GET', $params = [])
    {
        //请求接口
        $client = new \GuzzleHttp\Client([
            'timeout' => 60
        ]);
        if ($type === 'GET') {
            try {
                $res = $client->request($type, $url);
            } catch (\Exception $e) {
                return $this->errorReturn(10001, $e->getMessage());
            }
        } else if ($type === 'POST') {
            $res = $client->request('POST', $url, [
                'headers' => ["Content-Type" => "text/plain"],
                'json' => $params,
            ]);
            // 如果是post的话就处理结果
            return $res->getBody()->getContents();
        } else {
            return tips('error', '暂不支持此请求');
        }

        return \GuzzleHttp\json_decode($res->getBody()->getContents(), true);
    }
}
